package B刷题.排序;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author wei.zhao
 * @description: 23.合并K个升序链表
 * @date 2022年04月04日 15:14
 */
public class Code02_MergeKLists {

    /**
     * 注意：链表重新连接，一定要将尾节点的下一个节点置空
     */
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparing(e -> e.val));
        for (ListNode listNode : lists) {
            if (null != listNode) {
                queue.add(listNode);
            }
        }
        ListNode result = null;
        ListNode cur = null;
        while (!queue.isEmpty()) {
            ListNode node = queue.poll();
            if (result == null) {
                result = node;
                cur = node;
            } else {
                cur.next = node;
                cur = node;
            }
            if (node.next != null) {
                queue.add(node.next);
            }
        }
        if (cur != null) {
            cur.next = null;
        }
        return result;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }
    }

}
